#include <cstdlib>
#include <iostream>
#include "Logger.h"
#include "TcpServer.h"

using namespace std;

class EchoServer {
private:
    void OnConnected(const TcpConnectionPtr& conn) {
        LOG_INFO("have a new connection...");
        conn->Send("connect success!\n");
    }

    // void OnMessage(const TcpConnectionPtr& conn, Buffer* in_buffer) {
    //     string msg = in_buffer->RetrieveAllAsString();
    //     conn->Send(msg);
    // }
    void OnMessage(const TcpConnectionPtr& conn, Buffer* buf) {
        // std::string request = buf->RetrieveAllAsString();
        // bool isHttpRequest = (request.find("HTTP/1.1") != std::string::npos ||
        //                       request.find("GET") != std::string::npos || request.find("POST") != std::string::npos);

        // if (isHttpRequest) {
        //     std::string response_body = "Hello from maplec Server!";
        //     std::string response =
        //         "HTTP/1.1 200 OK\r\n"
        //         "Content-Type: text/plain; charset=utf-8\r\n"
        //         "Content-Length: " +
        //         std::to_string(response_body.length()) +
        //         "\r\n"
        //         "Connection: keep-alive\r\n"
        //         "Server: maplec/1.0\r\n"
        //         "\r\n" +
        //         response_body;

        //     conn->Send(response);
        //     LOG_INFO("Sent HTTP 200 response with %zu bytes", response.length());
        // } else {
        //     // 非HTTP请求，也返回响应
        //     std::string response = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
        //     conn->Send(response);
        // }
        string msg = buf->RetrieveAllAsString();
        conn->Send(msg);
    }

    void SetThreadNum(int num = 3) { server_.SetThreadNum(num); }

public:
    EchoServer(EventLoop* loop, std::string name) : loop_(loop), server_(loop_, addr, name) {
        server_.SetConnectionCallback(bind(&EchoServer::OnConnected, this, placeholders::_1)),
            server_.SetMessageCallback(bind(&EchoServer::OnMessage, this, placeholders::_1, placeholders::_2));
    }

    void start() {
        SetThreadNum();
        server_.start();
    }

    ~EchoServer() {}

private:
    EventLoop* loop_;
    InetAddress addr;
    TcpServer server_;
};

int main() {
    // EventLoop loop;
    // EchoServer server(&loop, "EchoServer");
    // server.start();
    // loop.Loop();

    uint32_t port = 8080;
    std::string ip = "127.0.0.1";
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);

    // addr.sin_addr.s_addr = inet_addr(ip.c_str());
    inet_pton(AF_INET, ip.c_str(), &addr.sin_addr);

    char buf[32];
    inet_ntop(AF_INET, &addr.sin_addr, buf, sizeof(buf));
    printf("ip(x.x.x.x):port = %s:%d", buf, ntohs(addr.sin_port));

    return 0;
}